//
//  ZYWeChatLoginViewModel.m
//  YiLin
//
//  Created by Zyark on 2018/6/15.
//  Copyright © 2018年 Zyark. All rights reserved.
//

#import "ZYWeChatLoginViewModel.h"
#import "AFNetWorkUtils.h"
#import "ZYUser.h"

@implementation ZYWeChatLoginViewModel
-(RACCommand *)loginCommand{
    if(!_loginCommand){
        @weakify(self);
        _loginCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            @strongify(self);
            if(NULLString(self.code)){
                return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                    [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_ERROR_WECHAT_AUTHORIZATION_FAILURE]]];
                    [subscriber sendCompleted];
                    return nil;
                }];
            }
            NSDictionary *params = @{@"code":self.code};
            NSString *url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_WECHAT_LOGIN_URL];
            return [[AFNetWorkUtils racPOSTWithURL:url params:params] map:^id(id value) {
                NSDictionary *responseObject = value;
                ZYUser *user = [ZYUser modelWithJSON:[responseObject objectForKey:@"result"]];
                [ZYConfig saveUserInfo:user];
                return value;
            }];
        }];
    }
    return _loginCommand;
}
@end
